﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using sqlserverdemo.entitys;

namespace sqlserverdemo.orm
{
    internal class OrmUtils
    {
    }

    internal class MyDbContext : DbContext
    {
        internal DbSet<TUser> TUsers { get; set; }
        public DbSet<TAddr> TAddrs { get; set; }

        public DbSet<TRole> TRoles { get; set; }

        public DbSet<TDept> TDepts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=localhost;Database=test;User Id=sa;Password=881213;Encrypt=True;TrustServerCertificate=True;");
        }

        /// <summary>
        /// OnModelCreating 方法是 Entity Framework Core 中用于配置实体与数据库表映射关系的关键方法
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TUser>().ToTable("tuser");
            modelBuilder.Entity<TAddr>().ToTable("taddr");
            modelBuilder.Entity<TRole>().ToTable("trole");
            modelBuilder.Entity<TDept>().ToTable("tdept");


            // OnModelCreating
            modelBuilder.Entity<TUser>()
                .HasOne(u => u.Dept)
                .WithOne(d => d.User)
                .HasForeignKey<TUser>(u => u.DeptId);

            // 一对多关系配置，指定外键字段名
            modelBuilder.Entity<TUser>()
                .HasMany(u => u.Addrs)
                .WithOne(a => a.User)
                .HasForeignKey(a => a.UserId);



            
            // 多对多关系配置，指定中间表和字段名
            modelBuilder.Entity<TUser>()
                .HasMany(u => u.Roles)
                .WithMany(r => r.Users)
                .UsingEntity<Dictionary<string, object>>(
                    "tuser_role",
                    j => j.HasOne<TRole>().WithMany().HasForeignKey("RoleId"),
                    j => j.HasOne<TUser>().WithMany().HasForeignKey("UserId")
                );
        }
    }
}
